package com.itwn.controller;

import com.itwn.bean.User;
import com.itwn.bean.UserRoles;
import com.itwn.service.UserService;
import com.itwn.util.PassUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.time.Year;
import java.util.UUID;

/**
 * @Description:
 * @ClassName: UserController
 * @Author: 流光亦断
 * @Date: 2021/8/20 11:29
 * @Version: 1.0     // 版本
 */
@Controller
public class UserController {
    @Autowired
    private UserService service;


    @RequestMapping("/userlogin")
    public String login(String userNo, String userPass) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userNo, userPass);
        try {
            subject.login(token);
            return "main";
        } catch (UnknownAccountException e) {
            System.err.println(e.getMessage());
        } catch (IncorrectCredentialsException e) {
            System.err.println("密码认证失败");
        } catch (AuthenticationException e) {
            System.err.println("其他认证异常...");
        }
        return "login";
    }

    @RequestMapping("/reg")
    public String doRegister(User user, String repeatPass) {
        if (user.getUserPass().equals(repeatPass)) {
            user.setSaltValue(UUID.randomUUID().toString().replace("-", ""));
            user.setCodePass(PassUtil.getHashPass("MD5", user.getUserPass(), user.getSaltValue(), 1023));
            if (service.doRegister(user) > 0) {
                //根据账户查询ID
                UserRoles userRoles = new UserRoles();
                userRoles.setUserId(service.queryIdByNo(user.getUserNo()));
                if (service.addUserRoles(userRoles) > 0) {
                    return "login";
                }
            }
        }
        return "register";
    }

}
